<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\job;

use app\BaseController;
use think\facade\Db;
use app\wework\model\BaseModel;
use app\wework\model\QyWechatApi;
use think\facade\Log;
use think\queue\Job;


/**
	* 群Sop任务类
*/
class GroupSop extends BaseController{
	public function index(){
		$config_list = Db::table('kt_wework_config')->where(["customer_status"=>1])->column("wid");
        if(!$config_list) return success("操作失败");
        foreach ($config_list as $user) {
           $this->sop($user);
        }
        return success("操作成功");
	}

	public function sop($wid){
		$list = Db::table("kt_wework_groupsop")->where(["wid"=>$wid,"status"=>1])->json(["group_condition_tag","groupid"])->select()->toArray();
		foreach ($list as $value){
			$detail_list = Db::table("kt_wework_groupsop_detail")->where(["pid"=>$value["id"]])->select()->toArray();
			foreach ($detail_list as $detail){
				if($detail["type"] == 1)$time = time() - $detail["size"] * 3600 - $detail["time"]*60;
				if($detail["type"] == 2){
					if(date("H:i:s") < $detail["time"])continue;
					$time = strtotime(date("Y-m-d")) - $detail["size"] * 86400;
				}
				if($detail["type"] == 3){
					$wk_day = date('w');
					if($wk_day != $detail["week"])continue;
					if(date("H:i:s") < $detail["time"])continue;
					$time = strtotime(date("Y-m-d")) - $detail["size"] * 604800;
				}
				$time = date("Y-m-d H:i:s",$time+86400);
				$group_list = Db::table("kt_wework_groupsop_time")->where(["pid"=>$value["id"],"type"=>0])->whereTime('ctime','<=',$time)->select()->toArray();
				if($group_list){
					$ids = array_column($group_list, "id");
					$group_id = array_column($group_list, "group_id");
					$group_list = Db::table("kt_wework_group")->where(["chat_id"=>$group_id,"wid"=>$wid])->select()->toArray();
					foreach ($group_list as $group){
                    	$send = "管理员创建了推送任务，提醒你给客户群『".$group["name"]."』发送应用消息";
						$send_res = QyWechatApi::send_textcard($group["owner"],$wid,"群SOP提醒",$send,$this->request->domain().'/wework/h5.GroupSop/index.html?id='.$detail["id"]);
					}
					Db::table("kt_wework_groupsop_time")->where(["id"=>$ids])->update(["type"=>1]);
				}
			}
		}
		return success("操作成功");
	}
}